from django.shortcuts import render
import re
import random
import string
import redis
from django.contrib.auth.hashers import make_password,check_password
from captcha.image import ImageCaptcha
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from.models import Users
class checkNameV(APIView):
    def get(self,request,username):
        if not username:
            return Response({'code':400,'msg':'用户名为空'})
        if not re.findall(r"[a-zA-Z][a-zA-Z0-9]{4,15}$",username):
            return Response({'code':400,'msg':'用户名不符合规则'})
        if Users.objects.filter(username=username).count()>0:
            return Response({'code': 400, 'msg': '用户名已存在'})
        return Response({'code':200,'msg:':'用户名校验成功'})


class checkMobileV(APIView):
    def get(self,request,mobile):
        if not mobile:
            return Response({'code':400,'msg':'手机号为空'})
        if not re.findall(r"1[3-9][0-9]{9}$",mobile):
            return Response({'code':400,'msg':'手机号不符合规则'})
        if Users.objects.filter(username=mobile).count()>0:
            return Response({'code': 400, 'msg': '手机号已存在'})
        return Response({'code':200,'msg:':'手机号校验成功'})

class checkImageV(APIView):
    def get(self,request,uuid):
        str_num=''.join(random.sample(string.ascii_letters+string.digits,4))
        r=redis.Redis(host='localhost',port=6379,db=5)
        r.set(uuid,str_num,ex=120)
        # r.close()
        cap=ImageCaptcha()
        img=cap.generate(str_num)
        return HttpResponse(content_type='image/png',content=img)
    def post(self,request,uuid):
        code1=request.data.get('uuid')
        r=redis.Redis(host='localhost',port=6379,db=5)
        print(r,"----------------------------")
        code2=r.get(uuid)
        # r.close()
        if code2:
            aa=code2.decode()
        else:
            return Response({'code': 400, 'msg:': '验证码已过期'})
        if aa.lower()!=code1.lower():
            return Response({'code': 400, 'msg:': '验证码输入错误'})
        return Response({'code':200,'msg':'图片验证码校验成功'})

class RegisterV(APIView):
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        password2=request.data.get('password2')
        mobile=request.data.get('mobile')
        agree=request.data.get('agree')

        if not all([username,password,password2,mobile,agree]):
            return Response({'code':400,'msg':'字段不完整'})
        if password2!=password:
            return Response({'code': 400, 'msg': '两次的密码不正确'})
        if not mobile:
            return Response({'code':400,'msg':'手机号不能为空'})
        if not agree:
            return Response({'code': 400, 'msg': '请勾选用户协议'})
        pwd= make_password(password)
        Users.objects.create(
            username=username,password=pwd,mobile=mobile
        )

        return Response({'code':200,'msg':'注册成功'})


from django.db.models import Q
import jwt
from wlgday5.settings import SECRET_KEY
def jwt_div(user):
    property={
        'id':user.id,
        'username':user.username,
    }
    token=jwt.encode(payload=property,key=SECRET_KEY,algorithm='HS256')
    return token
class LoginV(APIView):
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        print(username,password ,"------------------------------------------------")
        user=Users.objects.filter(Q(username=username)|Q(mobile=username))
        print(user,"------------------------------------------------")
        if not username:
            return Response({'code': 400, 'msg': '用户名不能为空'})

        if not user:
            return Response({'code':400,'msg':'用户不存在'})
        else:
            if not check_password(password,user.password[0]):
                return Response({'code':400,'msg':'密码不正确'})

            else:
                token = jwt_div(user[0])

                return Response({'code':200,'msg':'登录成功','token':token,'user':{'id':user.id,'username':user.username}})






























# import re
# import  random
# import string
# import redis
# from django.contrib.auth.hashers import make_password,check_password
# from captcha.image import ImageCaptcha
# from rest_framework.views import APIView
# from django.http import HttpResponse
# from rest_framework.response import Response
# from .models import Users
#
# # Create your views here.
# class checkName(APIView):
#     def get(self,request,username):
#         if not username:
#             return Response({'code':400,'msg':'用户名不能为空'})
#         if not re.findall(r"[a-zA-Z0-9]{5,15}$",username):
#             return Response({'code':400,'msg':'用户名不符合规则'})
#         if Users.objects.filter(username=username).count()>0:
#             return Response({'code':400,'msg':'用户名已存在'})
#         return Response({'code':200,'msg':'用户名校验成功'})
#
# class checkMobile(APIView):
#     def get(self,request,mobile):
#         if not mobile:
#             return Response({'code': 400, 'msg': '手机号不能为空'},status=400)
#         if not re.findall(r"1[3-9][0-9]{9}$",mobile):
#             return Response({'code': 400, 'msg': '手机号不符合规则'},status=400)
#         if Users.objects.filter(mobile=mobile).count()>0:
#             return Response({'code': 400, 'msg': '手机号已存在'},status=400)
#         return Response({'code':200,'msg':'手机号校验成功'},status=200)
#
# class checkImage(APIView):
#     def get(self,request,uuid):
#         str_num=''.join(random.sample(string.ascii_letters+string.digits,4))
#         r=redis.Redis( host="localhost", port=6379, db=0)
#         r.set(uuid,str_num,ex=120)
#         r.close()
#         cap=ImageCaptcha()
#         img=cap.generate(str_num)
#         return HttpResponse(content=img,content_type='image/png')
#     def post(self,request,uuid):
#         code1=request.data.get('code')
#         r = redis.Redis(host="localhost", port=6379, db=0 )
#         code2=r.get(uuid)
#         r.close()
#         print(code2,"-----------------------------------------------")
#         if code2:
#             aa=code2.decode()
#         else:
#             return Response({'code':400,'msg':'验证码过期'},status=400)
#         if aa.lower() != code1.lower():
#             return Response({'code':400,'msg':'验证码错误'},status=400)
#         return  Response({'code':200,'msg':'验证码校验成功'},status=200)
#
# class Register(APIView):
#     def post(self,request):
#         username=request.data.get('username')
#         password=request.data.get('password')
#         password2=request.data.get('password2')
#         mobile=request.data.get('mobile')
#         agree=request.data.get('agree')
#         if not all([username,password,password2,mobile,agree]):
#             return Response({'code':400,'msg':'字段不完整'},status=400)
#         if not username:
#             return Response({'code': 400, 'msg': '用户名不能为空'},status=400)
#         if password !=password2:
#             return Response({'code': 400, 'msg': '两次输入的密码不一致'},status=400)
#         if not mobile:
#             return Response({'code':400,'msg':'手机号不为空'},status=400)
#         if not agree:
#             return Response({'code': 400, 'msg': '请勾选用户协议'}, status=400)
#         hash_pwd=make_password(password)
#         Users.objects.create(
#             username=username,password=hash_pwd,mobile=mobile
#         )
#         return Response({'code':200,'msg':'注册成功'})
#
# from django.db.models import Q
# import jwt
# from wlgday5 .settings import SECRET_KEY
# def get_jwt(user):
#     payload={
#         'id':user.id,
#         'username':user.username,
#         'mobile':user.mobile,
#     }
#     token=jwt.encode(payload=payload,key=SECRET_KEY,algorithm='HS256')
#     return token
# class Login(APIView):
#     def post(self,request):
#         username=request.data.get('username')
#         password=request.data.get('password')
#         try:
#             user=Users.objects.get(Q(username=username) | Q(mobile=username))
#         except Exception as e:
#             print(e)
#             return Response({'code':400,'msg':'用户不存在'})
#         token=get_jwt(user)
#         if not check_password(password,user.password ):
#             return Response({'code':400,'msg':'密码错误'})
#         return Response({'code':200,'msg':'登录成功','token':token,'user':{'id':user.id,'username':user.username}})









